package cn.ffcs.product.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse; 

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;


import com.opensymphony.xwork2.ActionContext;

import cn.ffcs.base.web.BaseAction;
import cn.ffcs.common.model.Attach;
import cn.ffcs.common.service.AttachService;
import cn.ffcs.product.model.Product;
import cn.ffcs.product.model.ProductReference;
import cn.ffcs.product.service.ProductReferenceService;
import cn.ffcs.product.service.ProductService;
import cn.ffcs.security.model.User;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.system.dict.model.DictType;
import cn.ffcs.system.dict.service.DictService;
import cn.ffcs.system.dict.service.DictTypeService;
import cn.ffcs.util.MyList;
import cn.ffcs.util.properties.PropertiesUtil;
import cn.ffcs.util.context.ApplicationContextUtil;

/**
 * 产品资料action层，实现页面业务逻辑<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">liuzhh</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author liuzhh
 * @version $Id$
 */
public class ProductReferenceAction<P extends ProductReference> extends
        BaseAction<P>
{
    private static final int BUFFER_SIZE = 512 * 1024;
    /** 业务POJO **/
    private P productReference;
    /** 产品 **/
    private Product product;
    /** 资料类型数据 **/
    private List<Dict> lRefType;
    /** 产品列表数据 **/
    private List<Product> products;
    /** 数据字典类型服务 **/
    private DictTypeService<DictType> dictTypeService;
    /** 数据字典服务 **/
    private DictService<Dict> dictService;
    /** 产品服务 **/
    private ProductService<Product> productService;
    /** 产品资料服务 **/
    private ProductReferenceService<P> productReferenceService;
    /** 资料类型ID **/
    private String referenceTypeId;
    /** 附件列表数据 **/
    private List<Attach> attachs;
    /** 附件服务 **/
    private AttachService<Attach> attachService;
    /** 附件上传 **/
    private List<File> uploads;
    /** ftp文件 **/
    private List<String> ftpFile;
    /** properties配置ftp路径 **/
    private String ftpUrl;


    /** 上传附件名称 **/
    private List<String> fileNames;
    /** 上传附件名称 **/
    private List<String> uploadContentTypes;
    /** 上传附件名称 **/
    private List<P> productReferences;
    /** 上传附件最大 **/
    private String ftpMaxSize;

    /**
     * 初始化业务数据
     * @return
     */
    @SuppressWarnings("unchecked")
    public String init()
    {

        // 根据实体名称获取字典类型
        String dtKey = new ProductReference().getClass().getSimpleName();

        Criterion condDt = Restrictions.eq("keyValue", dtKey.toUpperCase());

        List<DictType> ldt = this.dictTypeService.findBy(condDt);

        if (ldt != null && ldt.size() > 0)
        {
            DictType dictType = (DictType) ldt.get(0);
            Criterion cond = Restrictions.eq("dictType.id", dictType.getId());
            lRefType = dictService.findBy(cond);
        }
        else
        {
            lRefType = new ArrayList<Dict>();
        }
        // products=productService.findAll();

        if (productReference != null&&productReference.getId()!=null)
        {
            Criterion cond1 = Restrictions.eq("refEntity", productReference
                    .getClass().getName());
            Criterion cond2 = Restrictions.eq("refEntityID", productReference
                    .getId().toString());
            Criterion condAttach = Restrictions.and(cond1, cond2);
            attachs = attachService.findBy(condAttach);
        }

        this.setFtpUrl(PropertiesUtil.readValue(
                "/poc-ftp.properties", "ftp.url"));
        this.setFtpMaxSize(PropertiesUtil.readValue("/poc-ftp.properties","ftp.maxSize"));
        return SUCCESS;
    }

    /**
     * 保存操作
     * @return
     */
    public String saveOrUpdate()
    {
        //初始化数据
        init();     
        
        // 新增附件是否发布
        List<String> isPublishs = null;
        /** 是否有ftp上传 **/
        boolean isFtp = false;
        List<String> isFtps = null;
        /** ftpFile 
        List<String> ftpFile = null;**/
        if (uploads != null && uploads.size() > 0)
        {
            String[] cbPublishs = getContextObjects("isPublishs");
            String[] cbFtps = getContextObjects("isFtp");
            isPublishs = new ArrayList<String>();
            isFtps = new ArrayList<String>();
            for (String cbPublish : cbPublishs)
            {
                if (cbPublish.equalsIgnoreCase("1")
                        || cbPublish.equalsIgnoreCase("2"))
                {
                    if (cbPublish.equalsIgnoreCase("2"))
                    {
                        cbPublish = "0";
                    }
                    isPublishs.add(cbPublish);
                }
            }
            int i=0;
            for (i=0;i<uploads.size();i++)
            {
                String cbFtp = cbFtps[i];
                File file=uploads.get(i);
                if (!cbFtp.equalsIgnoreCase("2") && uploads.get(i).length() > Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("1");
                }
                if (!cbFtp.equalsIgnoreCase("2") && uploads.get(i).length() <= Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("0");
                }
                if (cbFtp.equalsIgnoreCase("2") && file.length() > Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("1");
                }
                if (cbFtp.equalsIgnoreCase("2") && file.length() <= Long.valueOf(this.ftpMaxSize))
                {
                    isFtps.add("0");
                }
                if (cbFtp.equalsIgnoreCase("1"))
                {
                    isFtp = true;
                }
            }
        }

        String[] publishIDs = getContextObjects("publishIDs");
        String[] attachIDs = getContextObjects("attachIDs");
        // 删除附件
        String[] delIDs = getContextObjects("delIDs");
        // 保存产品资料数据
        String contextPath = ServletActionContext.getServletContext().getRealPath("/");
        productReferenceService.saveProductReferenceInfo(contextPath,productReference,
                uploads, fileNames, publishIDs, attachIDs, delIDs, isPublishs,isFtps);
        // 初始化数据
        init();
        // 保存产品信息
        if (product != null && product.getId() != 0)
        {
            product = (Product) productService.findById(product.getId());
        }
        
        if(isFtp){
          //  return "ftpupload";
        }

        return SUCCESS;
    }

    /**
     * 根据产品id获取所有产品资料
     * @return
     */
    public String showProductDetail()
    {
        Criterion cond = Restrictions.eq("product.id", productReference
                .getProduct().getId());
        List<P> lpr = productReferenceService.findBy(cond);
        List<P> result = new ArrayList<P>();
        if (lpr != null && lpr.size() > 0)
        {
            for (P pr : lpr)
            {
                Criterion cond1 = Restrictions.eq("refEntity", pr.getClass()
                        .getName());
                Criterion cond2 = Restrictions.eq("refEntityID", pr.getId()
                        .toString());
                Criterion condAttach = Restrictions.and(cond1, cond2);
                pr.setAttachs(attachService.findBy(condAttach));
                result.add(pr);
            }
        }
        Product product = this.productService.findById(productReference
                .getProduct().getId());
        productReference.setProduct(product);
        productReferences = result;

        return SUCCESS;
    }

    /**
     * 根据产品名称获取产品资料信息
     * @return
     */
    @SuppressWarnings("unchecked")
    public String searchPR()
    {

        // 根据产品名称查找所有产品
        Criterion cond = null;
        if (super.getConds() != null)
        {
            // 遍历参数表
            Iterator i = super.getConds().entrySet().iterator();
            while (i.hasNext())
            {
                Entry entry = (Entry) i.next();
                String key = (String) entry.getKey();
                if (super.getConds().get(key) != null
                        && !StringUtils.isEmpty(super.getConds().get(key)
                                .toString()))
                {
                    // 根据实际情况做处理
                    Criterion temp = null;
                    if (key.equalsIgnoreCase("product.name"))
                    {
                        temp = Restrictions.like("name", "%"
                                + super.getConds().get(key).toString() + "%");
                    }
                    if (cond == null)
                    {
                        cond = temp;
                    }
                    else
                    {
                        cond = Restrictions.and(cond, temp);
                    }
                }
            }
        }
        // 翻页
        List<Product> pds = this.productService.findBy(cond);

        products = new ArrayList<Product>();
        // 根据产品获取产品资料
        if (pds != null && pds.size() > 0)
        {
            for (Product p : pds)
            {
                Criterion cpr = Restrictions.eq("product.id", p.getId());
                List<ProductReference> prs = (List<ProductReference>) this.productReferenceService
                        .findBy(cpr);
                p.setProductReferences(prs);
                products.add(p);
            }
        }

        return SUCCESS;
    }

    /**
     * 列表翻页
     * @return
     */
    public String findByPage()
    {
        // 根据实体名称获取字典类型
        String dtKey = new ProductReference().getClass().getSimpleName();
        Criterion condDt = Restrictions.eq("keyValue", dtKey.toUpperCase());
        List<DictType> ldt = this.dictTypeService.findBy(condDt);
        if (ldt != null && ldt.size() > 0)
        {
            DictType dictType = (DictType) ldt.get(0);
            Criterion cond = Restrictions.eq("dictType.id", dictType.getId());
            lRefType = dictService.findBy(cond);
        }
        else
        {
            lRefType = new ArrayList<Dict>();
        }

        return super.findByPage();
    }

    /**
     * 列表翻页
     * @return
     */
    public String findByPageANDuser()
    {
        // 根据实体名称获取字典类型
        String dtKey = new ProductReference().getClass().getSimpleName();
        Criterion condDt = Restrictions.eq("keyValue", dtKey.toUpperCase());
        List<DictType> ldt = this.dictTypeService.findBy(condDt);
        if (ldt != null && ldt.size() > 0)
        {
            DictType dictType = (DictType) ldt.get(0);
            Criterion cond = Restrictions.eq("dictType.id", dictType.getId());
            lRefType = dictService.findBy(cond);
        }
        else
        {
            lRefType = new ArrayList<Dict>();
        }

        HashMap<String, Object> conds = super.getConds();
        if (conds == null)
        {
            conds = new HashMap<String, Object>();
        }
        User currUser = ApplicationContextUtil.getUserContextObject()
                .getCurrUser();
        conds.put("creator", currUser.getUserID());
        super.setConds(conds);

        return super.findByPage();
    }

    /**
     * 组合查询条件
     * @return
     */
    public Criterion combineCond()
    {
        Criterion cond = null;
        if (super.getConds() != null)
        {
            // 遍历参数表
            Iterator i = super.getConds().entrySet().iterator();
            while (i.hasNext())
            {
                Entry entry = (Entry) i.next();
                String key = (String) entry.getKey();
                if (super.getConds().get(key) != null
                        && !StringUtils.isEmpty(super.getConds().get(key)
                                .toString()))
                {
                    // 根据实际情况做处理
                    Criterion temp = null;
                    if (key.equalsIgnoreCase("title")||key.equalsIgnoreCase("creator"))
                    {
                        temp = Restrictions.like(key, "%"
                                + super.getConds().get(key).toString() + "%");
                    }else if ( key.equalsIgnoreCase("product.name")){
                        //先查找对应产品ID
                        Criterion cProduct = Restrictions.like("name", "%"+super.getConds().get(key).toString()+"%");
                        List<Product> cproducts=productService.findBy(cProduct);
                        if (cproducts!=null && cproducts.size()>0){
                            Integer[] productIDs=new Integer[cproducts.size()];
                            int j=0;
                            for (Product p:cproducts){
                                productIDs[j]=p.getId();
                                j++;
                            }
                            temp=Restrictions.in("product.id", productIDs);
                        }else{
                            temp=Restrictions.eq("product.id", 0);
                        }
                    }
                    else if (key.equalsIgnoreCase("referenceType.id")
                            || key.equalsIgnoreCase("product.id"))
                    {
                        temp = Restrictions.eq(key, Integer.parseInt(super
                                .getConds().get(key).toString()));
                    }
                    else
                    {
                        temp = Restrictions.eq(key, super.getConds().get(key));
                    }

                    if (cond == null)
                    {
                        cond = temp;
                    }
                    else if (temp != null)
                    {
                        cond = Restrictions.and(cond, temp);
                    }
                }
            }
        }
        return cond;
    }
    
    /**
     * 统一检索产品资料查询
     * @return
     */
    public String toSetPicture()
    {
        return SUCCESS;
    }
    
    /**
     * 统一检索产品资料查询
     * @return
     */
    public String setPicture()
    {
        
        File file = uploads.get(0);
        String fileName = fileNames.get(0);
        String fullName = fileName;
        String name = fullName.substring(0, fullName.lastIndexOf("."));
        String prefix = fullName.substring(fullName.lastIndexOf(".") + 1,
                fullName.length());

        Long dateFile = new Date().getTime();
        String contextPath = ServletActionContext.getServletContext().getRealPath("/");
        String saveDirectory = contextPath
                + PropertiesUtil.readValue("/poc-ftp.properties", "ftp.path");
        // 保存绝对路径
        String saveFilePath = saveDirectory + fileName;
        try
        {
            FileUtils.copyFile(file, new File(saveFilePath));
            // byte[] result = new byte[BUFFER_SIZE];
            // result = FileUtils.readFileToByteArray(file);
    
            FileUtils.forceDelete(file);
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return SUCCESS;
    }
    
    
    /**
     * 统一检索产品资料查询
     * @return
     */
    public String singleSearch()
    {
        return findByPage();
    }

    /**
     * 删除操作
     * @return
     */
    public String remove()
    {
        baseService.remove(productReference);
        return SUCCESS;
    }

    /**
     * 统一维护删除操作
     * @return
     */
    public String removeProductReference()
    {
        ActionContext ctx = ActionContext.getContext();
        HttpServletResponse response = (HttpServletResponse) ctx
                .get(ServletActionContext.HTTP_RESPONSE);
        response.setCharacterEncoding("gb2312");// 页面编码设置
        response.setContentType("text/xml");// 页面文件头格式
        try
        {
            baseService.remove(productReference);
            response.getWriter().write(MyList.getStr("true"));
        }
        catch (Exception e)
        {
            try
            {
                response.getWriter().write(MyList.getStr("false"));
            }
            catch (Exception ee)
            {
            }
            e.printStackTrace();

        }
        return null;
    }

    /**
     * 批量删除操作
     * @return
     */
    public String batchDel()
    {
        String[] ids = getContextObjects("ids");
        baseService.batchDel(ids);
        return SUCCESS;
    }

    /**
     * 根据关键字获取实体数据
     * @return
     */
    public String findById()
    {
        if (productReference != null && productReference.getId() != 0)
        {
            productReference = (P) baseService.findById(productReference
                    .getId());
        }
        if (product != null && product.getId() != 0)
        {
            product = (Product) productService.findById(product.getId());
        }
        init();
        // /发布人默认为当前操作人员
        if (productReference == null || productReference.getCreator() == null
                || "".equals(productReference.getCreator()))
        {
            if (productReference == null)
            {
                ProductReference pp = new ProductReference();
                productReference = (P) pp;
                if(productReference!=null&&!"".equals(productReference)){
                    Dict dict=new Dict();
                    if (referenceTypeId!=null)
                        dict.setId(new Integer(referenceTypeId));
                    productReference.setReferenceType(dict);
                }
            }
            User currUser = ApplicationContextUtil.getUserContextObject()
                    .getCurrUser();
            if (currUser != null)
            {
                productReference.setCreator(currUser.getUserID());
            }
        }
        return SUCCESS;
    }

    /**
     * 根据关键字获取实体数据
     * @return
     */
    public String showInfoById()
    {
        if (productReference != null && productReference.getId() != 0)
        {
            productReference = (P) baseService.findById(productReference
                    .getId());
            String content = productReference.getContent();
            if (StringUtils.isNotEmpty(content))
            {
                content = content.replaceAll(" ", "&nbsp;");
                content = content.replaceAll("\n", "<br>");
                productReference.setContent(content);
            }
        }
        init();
        return SUCCESS;
    }

    /**
     * 获取业务POJO
     * @return
     */
    public P getProductReference()
    {
        return productReference;
    }

    /**
     * 设置业务POJO
     * @return
     */
    public void setProductReference(P productReference)
    {
        this.productReference = productReference;
    }

    /**
     * 获取资料类型数据
     * @return the lRefType
     */
    public List<Dict> getLRefType()
    {
        return lRefType;
    }

    /**
     * 设置资料类型数据
     * @param refType the lRefType to set
     */
    public void setLRefType(List<Dict> refType)
    {
        lRefType = refType;
    }

    /**
     * 获取数据字典服务
     * @return the dictService
     */
    public DictService getDictService()
    {
        return dictService;
    }

    /**
     * 设置数据字典服务
     * @param dictService the dictService to set
     */
    public void setDictService(DictService dictService)
    {
        this.dictService = dictService;
    }

    /**
     * 获取产品列表数据
     * @return the products
     */
    public List<Product> getProducts()
    {
        return products;
    }

    /**
     * 设置产品列表数据
     * @param products the products to set
     */
    public void setProducts(List<Product> products)
    {
        this.products = products;
    }

    /**
     * 获取数据字典服务
     * @return the productService
     */
    public ProductService getProductService()
    {
        return productService;
    }

    /**
     * 设置数据字典服务
     * @param productService the productService to set
     */
    public void setProductService(ProductService productService)
    {
        this.productService = productService;
    }

    /**
     * 获取附件列表数据
     * @return the attachs
     */
    public List<Attach> getAttachs()
    {
        return attachs;
    }

    /**
     * 设置附件列表数据
     * @param attachs the attachs to set
     */
    public void setAttachs(List<Attach> attachs)
    {
        this.attachs = attachs;
    }

    /**
     * 获取附件服务
     * @return the attachService
     */
    public AttachService getAttachService()
    {
        return attachService;
    }

    /**
     * 设置附件服务
     * @param attachService the attachService to set
     */
    public void setAttachService(AttachService attachService)
    {
        this.attachService = attachService;
    }

    public List<String> getUploadFileName()
    {
        return fileNames;
    }

    public void setUploadFileName(List<String> fileNames)
    {
        this.fileNames = fileNames;
    }

    public List<File> getUpload()
    {
        return uploads;
    }

    public void setUpload(List<File> uploads)
    {
        this.uploads = uploads;
    }

    public void setUploadContentType(List<String> contentTypes)
    {
        this.uploadContentTypes = contentTypes;
    }

    public List<String> getUploadContentType()
    {
        return this.uploadContentTypes;
    }

    /**
     * @return the productReferenceService
     */
    public ProductReferenceService getProductReferenceService()
    {
        return productReferenceService;
    }

    /**
     * @param productReferenceService the productReferenceService to set
     */
    public void setProductReferenceService(
            ProductReferenceService productReferenceService)
    {
        this.productReferenceService = productReferenceService;
    }

    /**
     * @return the dictTypeService
     */
    public DictTypeService<DictType> getDictTypeService()
    {
        return dictTypeService;
    }

    /**
     * @param dictTypeService the dictTypeService to set
     */
    public void setDictTypeService(DictTypeService<DictType> dictTypeService)
    {
        this.dictTypeService = dictTypeService;
    }

    /**
     * @return the productReferences
     */
    public List<P> getProductReferences()
    {
        return productReferences;
    }

    /**
     * @param productReferences the productReferences to set
     */
    public void setProductReferences(List<P> productReferences)
    {
        this.productReferences = productReferences;
    }

    public Product getProduct()
    {
        return product;
    }

    public void setProduct(Product product)
    {
        this.product = product;
    }

    public List<String> getFtpFile()
    {
        return ftpFile;
    }

    public void setFtpFile(List<String> ftpFile)
    {
        this.ftpFile = ftpFile;
    }

    public String getFtpUrl()
    {
        return ftpUrl;
    }

    public void setFtpUrl(String ftpUrl)
    {
        this.ftpUrl = ftpUrl;
    }
    

    public String getFtpMaxSize()
    {
        return ftpMaxSize;
    }

    public void setFtpMaxSize(String ftpMaxSize)
    {
        this.ftpMaxSize = ftpMaxSize;
    }

    public String getReferenceTypeId()
    {
        return referenceTypeId;
    }

    public void setReferenceTypeId(String referenceTypeId)
    {
        this.referenceTypeId = referenceTypeId;
    }

}
